import { DatePicker } from '@/components/AntdProxy';
import Crud from '@/components/Crud';
import { LineSelect } from '@/components/CustomForm';
import request from '@/utils/request';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Modal, Space, message } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import Detail from './components/Detail';
import Save from './components/Save';

const getList = async (params) => {
  const res = await request({
    url: '/datas/settlement/list',
    method: 'GET',
    custom: true,
    params: {
      ...params,
    },
  });
  return {
    total: res?.total,
    data: res?.data,
  };
};

const Index = () => {
  const [mode, setMode] = useState('list');
  const [record, setRecord] = useState();
  const [selectedRows, setSelectedRows] = useState([]);
  const crudRef = useRef();

  const deleteRow = (id) => {
    const ids = id ? [id] : selectedRows?.map?.((item) => item.settlementId);
    Modal.confirm({
      title: `确认删除所选数据?`,
      onOk: async () => {
        await request({
          url: '/datas/settlement/delete',
          method: 'POST',
          data: { ids },
        });
        message.success('操作成功');
        crudRef.current?.reload();
        setSelectedRows([]);
      },
    });
  };

  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: 65,
      render: (text, record, index) => index + 1,
    },
    {
      title: '线路',
      dataIndex: 'lineName',
      width: 150,
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 200,
    },
    {
      title: '结算日期',
      dataIndex: 'day',
      width: 120,
    },
    {
      title: '开始日期',
      dataIndex: 'fromDate',
      width: 150,
    },
    {
      title: '结束日期',
      dataIndex: 'toDate',
      width: 150,
    },
    {
      title: '磅单数',
      dataIndex: 'total',
      width: 200,
    },
    {
      title: '总金额',
      dataIndex: 'totalPrice',
      width: 200,
    },
    {
      title: '结算金额',
      dataIndex: 'price',
      width: 200,
    },
    {
      title: '差价',
      dataIndex: 'gapPrice',
      width: 200,
    },
    {
      title: '原因',
      dataIndex: 'reason',
      width: 200,
    },
    {
      title: '提交人',
      dataIndex: 'username',
      width: 200,
    },
    {
      title: '结算时间',
      dataIndex: 'receiveTime',
      width: 200,
    },
    {
      title: '结算人',
      dataIndex: 'receiveUser',
      width: 200,
    },
    {
      title: '系统时间',
      dataIndex: 'time',
      width: 200,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 200,
    },
    {
      title: '操作',
      fixed: 'right',
      dataIndex: 'operate',
      width: 140,
      render: (text, record) => {
        return (
          <Space>
            <a
              onClick={() => {
                setRecord(record);
                setMode('detail');
              }}
            >
              详情
            </a>
            <a
              onClick={() => {
                setRecord(record);
                setMode('edit');
              }}
            >
              编辑
            </a>
            <a
              onClick={() => {
                deleteRow(record.settlementId);
              }}
            >
              删除
            </a>
          </Space>
        );
      },
    },
  ];

  const fields = [
    {
      label: '线路',
      name: 'lineId',
      children: <LineSelect />,
    },
    {
      label: '开始时间',
      name: 'fromTime',
      children: <DatePicker placeholder="请选择开始时间" />,
    },
    {
      label: '结束时间',
      name: 'toTime',
      children: <DatePicker placeholder="请选择结束时间" />,
    },
  ];

  return (
    <>
      <Crud
        ref={crudRef}
        rowKey="settlementId"
        queryFormProps={{
          labelCol: 7,
          initialValues: {
            fromTime: dayjs().subtract(1, 'day'),
            toTime: dayjs(),
          },
        }}
        fields={fields}
        columns={columns}
        request={getList}
        transformParams={(params) => {
          return {
            ...params,
            fromTime: dayjs(params.fromTime).format('YYYY-MM-DD'),
            toTime: dayjs(params.toTime).format('YYYY-MM-DD'),
          };
        }}
        toolbar={
          <>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setMode('create')}
            >
              新增
            </Button>
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedRows.length === 0}
              onClick={() => deleteRow()}
            >
              批量删除
            </Button>
          </>
        }
        tableProps={{
          rowSelection: {
            selectedRowKeys: selectedRows?.map?.((item) => item.settlementId),
            onChange: (_, _selectedRows) => {
              setSelectedRows(_selectedRows);
            },
          },
        }}
      />
      <Save
        open={mode === 'create' || mode === 'edit'}
        record={record}
        onCancel={() => {
          setRecord();
          setMode('list');
        }}
        onOk={() => {
          setRecord();
          setMode('list');
          crudRef.current?.reload();
        }}
      />
      {mode === 'detail' && (
        <Detail
          open={mode === 'detail'}
          record={record}
          onCancel={() => {
            setRecord();
            setMode('list');
          }}
          onOk={() => {
            setRecord();
            setMode('list');
            crudRef.current?.reload();
          }}
        />
      )}
    </>
  );
};

export default Index;
